package com.huarun.module.repair.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.huarun.common.cos.PicUploadResult;
import com.huarun.common.cos.PicUploadService;
import com.huarun.common.cos.TC_COS_Config;
import com.qcloud.cos.COSClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.huarun.common.BASE64DecodedMultipartFile;
import com.huarun.common.BaseController;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.Constant;
import com.huarun.common.util.DateUtils;
import com.huarun.common.util.FastDFSUtil;
import com.huarun.common.util.HttpUtil;
import com.huarun.common.util.ResultCodeEnum;
import com.huarun.common.util.TokenUtil;
import com.huarun.module.applyrecord.bean.ApplyRecord;
import com.huarun.module.applyrecord.service.IApplyRecordService;
import com.huarun.module.repair.bean.AddResult;
import com.huarun.module.repair.bean.Pic;
import com.huarun.module.repair.bean.Repair;
import com.huarun.module.repair.bean.RepairApply;
import com.huarun.module.repair.bean.RepairRated;
import com.huarun.module.repair.bean.RepairRecord;
import com.huarun.module.repair.bean.WorkOrdersDetail;
import com.huarun.module.repair.bean.WorkOrdersFlow;
import com.huarun.module.repair.bean.WorkOrdersImgTable;
import com.huarun.module.repair.bean.WorkOrdersInfo;
import com.huarun.module.repair.service.IRepairApplyService;
import com.huarun.module.repair.service.IRepairRatedService;
import com.huarun.module.user.bean.User;
import com.huarun.module.user.service.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 报修申请
 * @author eva
 *
 */
@Api(description = "报修申请")
@RequestMapping("/wx/repair")
@RestController
public class RepairController extends BaseController {

	@Resource
	private IRepairApplyService repairApplyService;
//	@Autowired
//	FastDFSUtil fastDFSUtil;
	@Autowired
	private PicUploadService picUploadService;
	@Autowired
	private COSClient cosClient;
	@Autowired
	private TC_COS_Config tc_cos_config;
	@Resource
	private IRepairRatedService repairRatedService;

	@Resource
	private IApplyRecordService applyRecordService;

	@Resource
	private IUserService userService;

	@ApiOperation(value = "获取报修申请列表", notes = "报修申请列表")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<List<Repair>> Project_WorkOrders(HttpServletRequest request,
			@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer rows)
			throws Exception {
		ResponseMessage<List<Repair>> rm = new ResponseMessage<List<Repair>>();
		SimpleDateFormat sdf = DateUtils.sdfDateOnly;
		Map<String, Object> params = new HashMap<>();
		long time = System.currentTimeMillis();
		try {
			//每页条数，多少页、项目唯一编码/租户唯一标识/工单状态/开始日期/结束日期/描述（关键字）	
			String workorderstate = request.getParameter("workorderstate");
			String startTime = request.getParameter("startTime");
			String endTime = request.getParameter("endTime");
			String description = request.getParameter("description");
			String projectId = request.getHeader("projectId");
			//				String applyRowGuid=request.getHeader("RowGuid");
			String businessGuid = request.getHeader("synMainId");
			if (!"0".equals(workorderstate)) {
				params.put("workorderstate", workorderstate);
			}
			if (!(startTime == null || "".equals(startTime))) {
				params.put("startTime", startTime);
			}
			if (!(endTime == null || "".equals(endTime))) {
				params.put("endTime", endTime);
			}
			if (!(description == null || "".equals(description))) {
				params.put("description", description);
			}
			if (!(businessGuid == null || "".equals(businessGuid))) {
				params.put("BusinessGuid", businessGuid);
			}
			StringBuffer url = new StringBuffer(Constant.WORK_ORDER_LIST);
			//	url.append("20/1/1/6d5bd30a-d74d-45c4-9037-db332547aa6e");	
			//	url.append("200/1/");
			url.append(rows + "/" + page + "/" + projectId);
			String token = TokenUtil.createToken(url.toString(), request, time, params);
			Object[] keys = null;
			if (null != params) {
				keys = params.keySet().toArray();
				Arrays.sort(keys);
				if (null != keys) {
					url.append("?");
					for (Object key : keys) {
						Object value = params.get(key);
						url.append(key);
						url.append("=");
						url.append(String.valueOf(value));
						url.append("&");
					}
				}
				url.append("appkey=").append(Constant.MANAGE_APPKEY).append("&time=").append(time).append("&token=")
						.append(token);
			} else {
				url.append("?appkey=").append(Constant.MANAGE_APPKEY).append("&time=").append(time).append("&token=")
						.append(token);
			}
			System.out.println(url.toString());
			String url1 = Constant.BASE_URL + url.toString();
			String resultStr = HttpUtil.doGet(url1);
			if (null != resultStr) {
				JSONObject imisObj = JSONObject.parseObject(resultStr);
				String errorCode = imisObj.getString("ErrorCode");
				if ("0".equals(errorCode)) {
					JSONObject data = imisObj.getJSONObject("Data");
					JSONArray pageData = data.getJSONArray("pageData");
					List<Repair> list = JSON.parseObject(pageData.toJSONString(), new TypeReference<List<Repair>>() {});
					rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
					rm.setData(list);
				} else {
					JSONObject data = imisObj.getJSONObject("Data");
					String message = data.getString("FailReason");
					//rm.setCodeAndMsg(Integer.parseInt(errorCode),imisObj.getString("ErrorMessage")+message);
					rm.setCodeAndMsg(Integer.parseInt(errorCode), message);
				}
			} else {
				rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "网络异常");
			}

		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("报修申请列表异常！");
			e.printStackTrace();
		}
		return rm;
	}

	@ApiOperation(value = "获取申请列表", notes = "申请列表")
	@RequestMapping(value = "/list1", method = RequestMethod.GET)
	@ResponseBody
	public Object Project_WorkOrders1(HttpServletRequest request, Map<String, Object> params) throws Exception {
		long time = System.currentTimeMillis();
		String url = "/HuaRunCity.API/api/v1/ProjectLessee/GETLesseeInfoFromMoblie/18822858373";
		String token = TokenUtil.createToken(url, request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		String url1 = Constant.BASE_URL + url;
		String resultStr = HttpUtil.doGet(url1);
		return resultStr;
	}

	//http://localhost:6616/huarun/wx/repair/detail?workOrdersGuid=171d31e3-1e3b-1d32-3f8f-fed6dada1e84
	@ApiOperation(value = "获取保修申请详情", notes = "申请详情")
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<WorkOrdersDetail> Project_WorkOrderDetail(HttpServletRequest request,
			Map<String, Object> params) throws Exception {
		long time = System.currentTimeMillis();
		ResponseMessage<WorkOrdersDetail> rm = new ResponseMessage<WorkOrdersDetail>();
		//工单唯一标识：WorkOrdersGuid
		String workOrdersGuid = request.getParameter("workOrdersGuid");
		//String workOrdersGuid="f28245f9-1fc1-49c9-bd67-17b4c1234d88";
		RepairApply repairApply1 = repairApplyService.getByWorkOrdersGuid(workOrdersGuid);
		String url = Constant.WORK_ORDER_DETAIL + workOrdersGuid;
		String token = TokenUtil.createToken(url, request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		String resultStr = HttpUtil.doGet(Constant.BASE_URL + url);
		JSONObject imisObj = JSONObject.parseObject(resultStr);
		String erroeCode = imisObj.getString("ErrorCode");
		if ("0".equals(erroeCode)) {
			JSONObject data = imisObj.getJSONObject("Data");
			//工单基础信息
			JSONArray workOrdersInfo = data.getJSONArray("WorkOrdersInfo");
			List<WorkOrdersInfo> workOrdersInfolist = JSON.parseObject(workOrdersInfo.toJSONString(),
					new TypeReference<List<WorkOrdersInfo>>() {});
			WorkOrdersInfo orderInfo = new WorkOrdersInfo();
			RepairApply repairApply = new RepairApply();
			if (workOrdersInfolist.size() > 0) {
				orderInfo = workOrdersInfolist.get(0);
				repairApply.setRepairName(orderInfo.getRepairPerson() == null ? "" : orderInfo.getRepairPerson());
				repairApply.setTitle("报修申请");
				repairApply
						.setStatus(orderInfo.getWorkOrderStateName() == null ? "" : orderInfo.getWorkOrderStateName());
				repairApply.setCreateDate(orderInfo.getWorkTime() == null ? "" : orderInfo.getWorkTime());
				if (null != orderInfo.getWorkPlace()) {
					repairApply.setRepairLocation(orderInfo.getWorkPlace());
				} else if (null != orderInfo.getWorkPlaceRoomNames()) {
					repairApply.setRepairLocation(orderInfo.getWorkPlaceRoomNames());
				}
				repairApply.setRepairTime(orderInfo.getRepairTime() == null ? "" : orderInfo.getRepairTime());
				repairApply.setEndRepairTime(orderInfo.getEndRepairTime() == null ? "" : orderInfo.getEndRepairTime());
				if (null != repairApply1 && null != repairApply1.getRepairType()) {
					repairApply.setRepairType(repairApply1.getRepairType() == null ? "" : repairApply1.getRepairType());
				} else if (null != orderInfo.getFailureType()) {
					repairApply.setRepairType(orderInfo.getFailureType());
				} else {
					repairApply.setRepairType(orderInfo.getWorkType() == null ? "" : orderInfo.getWorkType());
				}
				repairApply.setRepairName(orderInfo.getRepairPerson() == null ? "" : orderInfo.getRepairPerson());
				repairApply
						.setRepairPhone(orderInfo.getRepairPersonTel() == null ? "" : orderInfo.getRepairPersonTel());
				repairApply.setRepairCompany(orderInfo.getBusinessName() == null ? "" : orderInfo.getBusinessName());
				repairApply.setDescription(orderInfo.getDescription() == null ? "" : orderInfo.getDescription());
				repairApply.setPic(repairApply1.getPic());
			}
			//工单流程信息
			JSONArray Imgs = data.getJSONArray("WorkOrdersImgTable");
			List<WorkOrdersImgTable> ImgList = JSON.parseObject(Imgs.toJSONString(),
					new TypeReference<List<WorkOrdersImgTable>>() {});
			RepairRated entity = repairRatedService.getByOrderNo(workOrdersGuid);
			WorkOrdersDetail workOrdersDetail = new WorkOrdersDetail();
			workOrdersDetail.setRepairApply(repairApply);
			workOrdersDetail.setWorkOrdersImgTable(ImgList);
			workOrdersDetail.setRepairRated(entity);
			rm.setData(workOrdersDetail);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} else {
			JSONObject data = imisObj.getJSONObject("Data");
			String message = data.getString("FailReason");
			//rm.setCodeAndMsg(Integer.parseInt(erroeCode),imisObj.getString("ErrorMessage")+message);
			rm.setCodeAndMsg(Integer.parseInt(erroeCode), message);
		}
		return rm;
	}

	@ApiOperation(value = "报修申请", notes = "新增保修工单")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Object Project_WorkOrderAdd(@RequestBody RepairApply repairApply, HttpServletRequest request)
			throws Exception {
		//添加一些非控判断
		ResponseMessage<Object> rm = new ResponseMessage<Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		String projectId = request.getHeader("projectId");
		String applyRowGuid = request.getHeader("RowGuid");
		if (StringUtils.isBlank(repairApply.getRepairTime())) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "预约修理时间不能为空");
			return rm;
		}
		//		if (StringUtils.isBlank(repairApply.getEndRepairTime())) {
		//			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "预约修理结束时间不能为空");
		//			return rm;
		//		}
		if (StringUtils.isBlank(repairApply.getDescription())) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "问题描述不能为空");
			return rm;
		}
		if (StringUtils.isBlank(repairApply.getRepairName())) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "联系人不能为空");
			return rm;
		}
		if (StringUtils.isBlank(repairApply.getRepairLocation())) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "报修地点不能为空");
			return rm;
		}

		StringBuffer allPath = new StringBuffer();
		List<Pic> list = new ArrayList<>();
		String[] files = repairApply.getFiles();
		try {
			//文件上传
			if (files != null && files.length > 0) {
				if (files.length > 9) {
					rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "最多只能上传9张");
					return rm;
				}
				for (int i = 0; i < files.length; i++) {
					MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(files[i]);
					Pic pic = new Pic();
					PicUploadResult uploadResult = picUploadService.upload(file);
					pic.setFileGuid(i + "");
					pic.setFileUrl(files[i]);
					String path = uploadResult != null ? uploadResult.getName() : "";
					allPath.append(path);
					allPath.append(",");
					list.add(pic);
				}
			}
			repairApply.setPic(allPath.toString());
			long time = System.currentTimeMillis();
			String url = Constant.WORK_ORDER_INSERT;
			SimpleDateFormat sdf = DateUtils.sdfDateTime;
			params.put("ProjectGuid", projectId);
			params.put("BusinessGuid", applyRowGuid);
			params.put("RepairTime", repairApply.getRepairTime());
			params.put("EndRepairTime", repairApply.getEndRepairTime());
			params.put("WorkTime", sdf.format(new Date()).toString());
			params.put("Description", repairApply.getDescription());
			params.put("RepairPerson", repairApply.getRepairName());
			params.put("RepairPersonTel", repairApply.getRepairPhone());
			params.put("WorkPlace", repairApply.getRepairLocation());
			params.put("FileContent", JSON.toJSONString(list));
			//			String token=TokenUtil.createToken(url,time, params);
			Map<String, Object> map = TokenUtil.createToken(url, time, params);
			String token = map.get("token").toString();
			url = url + "?token=" + token;
			params.put("appkey", Constant.MANAGE_APPKEY);
			params.put("time", time);
			params.put("FileContent", list);
			String json = JSON.toJSONString(params);
			System.out.println("json:" + json);
			//            String resultStr=HttpUtil.postGeneralUrl(Constant.BASE_URL+url, "application/json,text/json", json, "UTF-8");
			String resultStr = HttpUtil.postGeneralUrl(Constant.BASE_URL + url, "application/json,text/json",
					map.get("parms").toString(), "UTF-8");
			JSONObject imisObj = JSONObject.parseObject(resultStr);
			String errorCode = imisObj.getString("ErrorCode");
			if ("0".equals(errorCode)) {
				//更新工单唯一标识
				JSONObject data = imisObj.getJSONObject("Data");
				AddResult addResult = JSONObject.toJavaObject(data, AddResult.class);
				repairApply.setWorkOrdersGuid(addResult.getValue());
				repairApply.setCreateDate(sdf.format(new Date()));
				int count = repairApplyService.save(repairApply);
				ApplyRecord entity = new ApplyRecord();
				Map<String, Object> userParam = new HashMap<String, Object>();
				userParam.put("openId", request.getHeader("openId"));
				User user = userService.getUserByParams(userParam);
				userService.getUserByParams(userParam);
				entity.setPhone(repairApply.getRepairPhone());
				entity.setUserId(user.getId());
				entity.setRepairType(repairApply.getRepairType());
				entity.setTitle("报修申请");
				entity.setCreateDate(new Date());
				entity.setOperateNo(addResult.getValue());
				entity.setApplyType("报修申请");
				entity.setTypeCode(1);
				entity.setStatus("已提交");
				entity.setDescription(repairApply.getDescription());
				entity.setLocation(repairApply.getLocation());
				entity.setProjectId(request.getHeader("projectId"));
				entity.setSynId(request.getHeader("synId"));

				entity.setSynMainId(request.getHeader("synMainId"));
				applyRecordService.save(entity);
				log.info("更新{}条数据！", count);
				rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			} else {
				JSONObject data = imisObj.getJSONObject("Data");
				String message = data.getString("FailReason");
				//rm.setCodeAndMsg(Integer.parseInt(errorCode),imisObj.getString("ErrorMessage")+message);
				rm.setCodeAndMsg(Integer.parseInt(errorCode), message);
			}
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("报修申请异常！");
			e.printStackTrace();
		}
		return rm;
	}

	@ApiOperation(value = "获取报修申请进度", notes = "报修申请进度")
	@RequestMapping(value = "/schedule", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<WorkOrdersDetail> Project_WorkOrderSchedule(HttpServletRequest request,
			Map<String, Object> params) throws Exception {
		long time = System.currentTimeMillis();
		ResponseMessage<WorkOrdersDetail> rm = new ResponseMessage<WorkOrdersDetail>();
		//String workOrdersGuid="f28245f9-1fc1-49c9-bd67-17b4c1234d88";
		String workOrdersGuid = request.getParameter("workOrdersGuid");
		RepairApply repairApply1 = repairApplyService.getByWorkOrdersGuid(workOrdersGuid);
		String url = Constant.WORK_ORDER_DETAIL + workOrdersGuid;
		String token = TokenUtil.createToken(url, request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		String resultStr = HttpUtil.doGet(Constant.BASE_URL + url);
		JSONObject imisObj = JSONObject.parseObject(resultStr);
		String erroeCode = imisObj.getString("ErrorCode");
		if ("0".equals(erroeCode)) {
			JSONObject data = imisObj.getJSONObject("Data");
			//工单基础信息
			JSONArray workOrdersInfo = data.getJSONArray("WorkOrdersInfo");
			List<WorkOrdersInfo> workOrdersInfolist = JSON.parseObject(workOrdersInfo.toJSONString(),
					new TypeReference<List<WorkOrdersInfo>>() {});
			WorkOrdersInfo orderInfo = new WorkOrdersInfo();
			RepairApply repairApply = new RepairApply();
			if (workOrdersInfolist.size() > 0) {
				orderInfo = workOrdersInfolist.get(0);
				repairApply.setRepairName(orderInfo.getRepairPerson());
				repairApply.setTitle("报修申请");
				repairApply.setStatus(orderInfo.getWorkOrderStateName());
				repairApply.setCreateDate(orderInfo.getWorkTime());
				repairApply.setRepairLocation(orderInfo.getWorkPlace());
				repairApply.setRepairTime(orderInfo.getRepairTime());
				repairApply.setEndRepairTime(orderInfo.getEndRepairTime());
				if (null != repairApply1 && null != repairApply1.getRepairType()) {
					repairApply.setRepairType(repairApply1.getRepairType());
				}
				repairApply.setRepairName(orderInfo.getRepairPerson());
				repairApply.setRepairPhone(orderInfo.getRepairPersonTel());
				repairApply.setRepairCompany(orderInfo.getBusinessName());
				repairApply.setDescription(orderInfo.getDescription());
				//	repairApply.setPic(repairApply1.getPic());
			}
			//工单流程信息
			JSONArray workOrdersFlow = data.getJSONArray("WorkOrdersFlow");
			List<WorkOrdersFlow> list = JSON.parseObject(workOrdersFlow.toJSONString(),
					new TypeReference<List<WorkOrdersFlow>>() {});
			JSONArray repairRecord = data.getJSONArray("RepairRecord");
			List<RepairRecord> repairRecordList = JSON.parseObject(repairRecord.toJSONString(),
					new TypeReference<List<RepairRecord>>() {});
			WorkOrdersDetail workOrdersDetail = new WorkOrdersDetail();
			workOrdersDetail.setWorkOrdersFlowList(list);
			workOrdersDetail.setRepairApply(repairApply);
			workOrdersDetail.setRepairRecordList(repairRecordList);
			rm.setData(workOrdersDetail);
			rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		} else {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
		}
		return rm;
	}
}
